//
//  YMSocketSwift.swift
//  ThailandBus
//
//  Created by lantaiyuan on 2017/6/29.
//  Copyright © 2017年 youmy. All rights reserved.
//

import UIKit
import SocketRocket

/// Websocket管理工具
class YMSocketSwift: NSObject {
    
    static let shared = YMSocketSwift()
    
    typealias suncess = (_ message: AnyObject) -> Void
    
    typealias failure = (_ message: String) -> Void
    
    typealias isConnect = (_ flag: Bool) -> Void
    
    typealias closeClosure = () -> Void
    
    var successClosure:suncess?
    
    var failureClosure:failure?
    
    var isConnectClosure:isConnect?
    
    var closedSocket:closeClosure?
    
    
    var socket:SRWebSocket?
}

extension YMSocketSwift {
    
    /// 连接WebSocket
    func connect() {
        
        close()
        
        let sessionID = getRandomStringOfLength(length: 32)
        
        let url = URL(string: "ws://58.82.168.178:8211/lty-video-service/websocket/socketServer.ws?sessionID=\(sessionID)")
        
        // Test
        //        let url = URL(string: "ws://220.231.189.27:9001/lty-video-service/websocket/socketServer.ws?sessionID=\(sessionID)")
        
        socket = SRWebSocket(urlRequest: URLRequest(url: url!))
        socket?.delegate = self as SRWebSocketDelegate
        socket?.open()
    }
    
    /// 连接WebSocket
    func connect(server:String?, port:String?, userId:String?) {
        
        close()
        
        var urlStr = ""
        
        if let userId = userId, let server = server, let port = port {
            urlStr = "ws://\(server):\(port)"
            
            if userId.characters.count > 0 {
                urlStr = "ws://\(server):\(port)?userId=\(userId)"
            }
        }
        
        let url = URL(string: urlStr)
        
        socket = SRWebSocket(urlRequest: URLRequest(url: url!))
        socket?.delegate = self as SRWebSocketDelegate
        socket?.open()
    }
    
    /// 关闭WebSocket
    func close() {
        socket?.delegate = nil
        socket?.close()
        socket = nil
        
        if (closedSocket != nil) {
            closedSocket?()
        }
    }
    
    /// 发送数据
    ///
    /// - Parameter json: json字符串
    func send(json: String) {
        socket?.send(json)
    }
}

extension YMSocketSwift {
    
    
    /**
     生成随机字符串,
     
     - parameter length: 生成的字符串的长度
     
     - returns: 随机生成的字符串
     */
    func getRandomStringOfLength(length: Int) -> String {
        let characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        var ranStr = ""
        for _ in 0..<length {
            let index = Int(arc4random_uniform(UInt32(characters.characters.count)))
            ranStr.append(characters[characters.index(characters.startIndex, offsetBy: index)])
        }
        return ranStr
        
    }
}

extension YMSocketSwift: SRWebSocketDelegate {
    
    func webSocketDidOpen(_ webSocket: SRWebSocket!) {
        print("Websocket Connected")
        
        if (isConnectClosure != nil) {
            isConnectClosure!(true)
        }
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didReceiveMessage message: Any!) {
        
        print("SocketMessage:\(message)")
        
        if (successClosure != nil) {
            successClosure!(message as AnyObject)
        }
        
    }
    
    func webSocket(_ webSocket: SRWebSocket!, didFailWithError error: Error!) {
        print("Websocket Failed With Error:\(error)")
        if (failureClosure != nil) {
            failureClosure!(error.localizedDescription)
        }
        
        if (isConnectClosure != nil) {
            isConnectClosure!(false)
        }
    }
}
